<?php

namespace platform\models;

use common\enum\Enum;
use common\models\Car;
use common\models\Circuit;
use common\models\CircuitAddress;
use common\models\Notice;
use common\models\OpenCity;
use common\models\OrderCar;
use common\models\OrderChangeAudit;
use common\models\OrderNotice;
use common\models\OrderPassenger;
use common\models\PointTime;
use common\models\Shift;
use common\models\Site;
use common\models\SysManager;
use common\services\Authorization;
use platform\core\BaseModel;
use cm;
use Yii;
use yii\db\Expression;
use yii\db\Query;
use yii\helpers\Url;
use PHPExcel_IOFactory;
use PHPExcel_Style_Alignment;
use PHPExcel_Cell_DataType;
use common\models\Order;
class OrderModel extends BaseModel
{
    /*
    * 订单管理
    */
    public function actionIndex()
    {
        $this->refreshorder();
        if (Cm::$req->isPost()) {
            $action = Cm::$req->get('action');
            switch ($action) {
                case "list":
                    $page = Cm::$req->post('page', ['null', 'empty', 'default' => 1]);
                    $size = Cm::$req->post('limit', ['null', 'empty', 'default' => 20]);
                    $params=Yii::$app->request->post();

                    $query=Order::find()->alias('o')
                        ->leftJoin(['s'=>Shift::tableName()],['o.shift_id'=>new Expression('s.id')])
                        ->leftJoin(['c'=>Circuit::tableName()],['o.circuit_id'=>new Expression('c.id')])
                        ->select(['o.*','c.name as circuit_name','c.s_address','s.departuretime','s.inspector'])
                        ->andWhere(['s.status'=>Enum::STATUS_NORMAL,'c.status'=>Enum::STATUS_NORMAL]);

                    if(!empty($params['order_status']))$query->andWhere(['o.order_status'=>$params['order_status']]);

                    if(!empty($params['status']))$query->andWhere(['o.status'=>$params['status']]);

                    if(!empty($params['plate'])){
                        $order_ids=OrderCar::find()->andWhere(['car_id'=>$params['plate']])->select(['order_id'])->groupBy('order_id')
                        ->column();
                        $query->andWhere(['o.id'=>$order_ids]);
                    }

                    if(!empty($params['circuit']))$query->andWhere(['o.circuit_id'=>$params['circuit']]);

                    if(!empty($params['key']) || (isset($params['key'])&&$params['key'] == 0)){
                        $order_ids=OrderPassenger::find()->andWhere(['or',
                            ['like','name',$params['key']],
                            ['like','telephone',$params['key']],
                            ['like','id_card',$params['key']],
                        ])->select(['order_id'])->groupBy('order_id')->column();
                        $query->andWhere([
                            'or',
                            ['like','o.order_number',$params['key']],
                            ['o.id'=>$order_ids]
                        ]);
                    }

                    if(!empty($params['type']))$query->andWhere(['s.type'=>$params['type']]);

                    if(!empty($params['departuretime'])){
                        $departuretimearr = explode("至", $params['departuretime']);
                        $stime = trim($departuretimearr[0]);
                        $etime = trim($departuretimearr[1]);
                        $query->andWhere(['between','s.departuretime',$stime,$etime]);
                    }

                    if (!empty($params['ssite']))$query->andWhere(['c.site_sid'=>$params['ssite']]);

                    if (!empty($params['esite']))$query->andWhere(['c.site_eid'=>$params['esite']]);

                    $data['count']=$query->count();
                    $data['data']=$query->limit($size)->offset(($page - 1) * $size)
                         ->orderBy('o.addtime desc')->asArray()->all();

                    $inspector_ids=array_filter(array_unique(array_column($data['data'],'inspector')));
                    $sys_manager=[];
                    if(count($inspector_ids)){
                        $sys_manager=SysManager::find()->andWhere(['id'=>$inspector_ids])
                            ->select(['username'])->indexBy('id')->column();
                    }
                    $pt_ids=array_filter(array_unique(array_column($data['data'],'p_id')));
                    $departuretime=[];
                    if(count($pt_ids)){
                        $departuretime=PointTime::find()->andWhere(['id'=>$pt_ids])->select(['departuretime'])->indexBy('id')->column();
                    }
                    $s_id=array_filter(array_unique(array_column($data['data'],'s_id')));
                    $address=CircuitAddress::find()
                        ->andWhere(['id'=>$s_id])
                        ->select(['address','id'])
                        ->indexBy('id')->column();
                    foreach ($data['data'] as $key => &$value) {
                        $change_list = Cm::$db->one("SELECT id FROM order_change_audit WHERE order_id={$value['id']} AND status=1");
                        $value['change_list'] = empty($change_list) ? 0 : 1;
                        $value['departuretime']=$departuretime[$value['p_id']]??$value['departuretime'];
                        $value['s_address']=$address[$value['s_id']]??$value['s_address'];
                        $value['inspector']=$sys_manager[$value['inspector']]??'';
                    }
                    Cm::$res->paging($data);
                    break; 
                case 'info':
                    $id = (int)Cm::$req->post('id', ['null', 'empty', 'default' => 0]);
                    $info = Cm::$db->one("SELECT a.*,b.type as shifttype,c.name as circuitname,c.mileage,coa.name AS citysname,cob.name AS cityename,sa.name AS sitesname,sb.name AS siteename,b.departuretime,u.name,u.nickname,c.s_address,c.e_address 
                                        FROM `order` a 
                                        LEFT JOIN shift b ON a.shift_id=b.id 
                                        LEFT JOIN circuit c  ON a.circuit_id=c.id
                                        LEFT JOIN open_city coa ON coa.code=c.city_scode 
                                        LEFT JOIN open_city cob ON cob.code=c.city_ecode
                                        LEFT JOIN site sa ON sa.id=c.site_sid 
                                        LEFT JOIN site sb ON sb.id=c.site_eid 
                                        LEFT JOIN user u ON u.id=a.user_id
                                        WHERE a.id={$id} AND b.status=1 AND c.status=1 AND coa.status=1 AND cob.status=1 AND sa.status=1 AND sb.status=1");
                    if(empty($info)){
                        Cm::$res->error("获取订单详情失败");
                    }else{
                        $info['name'] = empty($info['name']) ? $info['nickname'] : $info['name'];
                        if($info['s_id']&&$info['e_id']){
                            $site_ids=CircuitAddress::find()
                                ->andWhere(['id'=>[$info['s_id']/*,$info['e_id']*/]])
                                ->select(['site_id'])
                                ->indexBy('id')
                                ->column();
                            $info['s_address']=Site::find()->andWhere(['id'=>$site_ids[$info['s_id']]])->select(['name as address'])->scalar();
//                            $info['e_address']=Site::find()->andWhere(['id'=>$site_ids[$info['e_id']]])->select(['name as address'])->scalar();
                        }
                        $car = Cm::$db->one("SELECT b.plate,c.username AS name,c.account AS telephone FROM order_car a
                                            LEFT JOIN car b ON b.id=a.car_id
                                            LEFT JOIN sys_manager c ON c.id=a.inspector
                                            WHERE a.order_id={$id} AND a.status=1");
                        $car = empty($car) ? '' : $car;
                        $passenger = Cm::$db->all("SELECT name,telephone,id_card,seat_number,is_check,seat_number FROM order_passenger WHERE order_id={$id} ");
                        if($info['p_id']){
                            $point=PointTime::findOne($info['p_id']);
                            $info['departuretime']=$point->departuretime;
                        }
                        Cm::$res->susess(['info'=>$info,'car'=>$car,'passenger'=>$passenger]);
                    }
                    break;    
                case 'save':
                    try {
                        $circuit_id = Cm::$req->post('circuit_id', ['null', 'empty', 'default' => 0]);
                        $shift_id = Cm::$req->post('shift_id', ['null', 'empty', 'default' => 0]);
                        $inspector = Cm::$req->post('inspector_id', ['null', 'empty', 'default' => 0]);
                        $car_id = Cm::$req->post('car_id', ['null', 'empty', 'default' => 0]);
                        $passenger = Cm::$req->post('passenger', ['null', 'empty', 'default' => '']);
                        $order = Cm::$req->post('order', ['null', 'empty', 'default' => '']);
                        if (empty($circuit_id)) {
                            Cm::$res->error("请选择路线");
                        }
                        if (empty($shift_id)) {
                            Cm::$res->error("请选择班次");
                        }
                        if (empty($inspector)) {
                            Cm::$res->error("请选择检票工作人员");
                        }
                        if (empty($car_id)) {
                            Cm::$res->error("请选择车辆");
                        }
                        $passenger = empty($passenger) ? [] : json_decode($passenger,true);
                        $order = empty($order) ? [] : json_decode($order,true);
                        if (empty($passenger) || empty($order)) {
                            Cm::$res->error("请选择乘客");
                        }
                        $time = date("Y-m-d H:i:s",time());
                        $cardata = [
                            'circuit_id' => $circuit_id,
                            'shift_id' => $shift_id,
                            'inspector' => $inspector,
                            'car_id' => $car_id,
                            'status'=>1,
                            'addtime' => $time,
                            'updatetime' => $time
                        ];

                        $ishas = Cm::$db->one("SELECT GROUP_CONCAT(order_id) AS orderids FROM order_car WHERE car_id={$car_id} AND shift_id={$shift_id}");
                        $orderidarr = empty($ishas['orderids']) ? [] : explode(",", $ishas['orderids']);
                        $updateorder = [];
                        foreach ($order as $key => $value) {
                            $cardata['order_id'] = $value;
                            if(!empty($orderidarr) && in_array($value, $orderidarr)){
                                continue;
                            }
                            $id = Cm::$db->insert('order_car', $cardata);
                            if($id){
                                $updateorder[] = $value;
                                Cm::$db->update('order', ['updatetime'=>$time,'order_status'=>2]," id={$value}");
                            }
                        }
                        $seat_number = Cm::$db->one("SELECT seat_number FROM order_passenger WHERE car_id={$car_id} AND status=1 AND shift_id={$shift_id} ORDER BY seat_number DESC");
                        $ishas = Cm::$db->one("SELECT GROUP_CONCAT(id) AS ids FROM order_passenger WHERE car_id={$car_id} AND status=1 AND seat_number!=0 AND shift_id={$shift_id}");
                        $idsarr = empty($ishas['ids']) ? [] : explode(",", $ishas['ids']);
                        $seat_number = empty($seat_number) ? 0 : $seat_number['seat_number'];
                        foreach ($passenger as $key => $value) {
                            if(empty($idsarr) || (!in_array($value, $idsarr) && !empty($idsarr))){
                                $seat_number++;
                                $mdata = [
                                    'updatetime' =>$time,
                                    'car_id'=>$car_id,
                                    'seat_number'=>$seat_number
                                ];
                                Cm::$db->update('order_passenger', $mdata," id={$value}");
                            }
                        }
                        Cm::$app->log->authlog(41,['passenger'=>$passenger,'order'=>$order,'cardata'=>$cardata],"批量派车");
                        /*发送派车模板消息*/
                        if(!empty($updateorder)){
                            $TemplateData = [
                                'order' => $updateorder
                            ];
                            Cm::$libs->wechat->sendTemplate('sendcar',$TemplateData);
                        }
                    }catch (\Exception $e){
                        Cm::$res->error($e->getMessage());
                    }
                    Cm::$res->susess([], '保存成功');
                    break;  
                case 'sendcar':
                    $ischeck = Cm::$req->post('ischeck', ['null', 'empty', 'default' => 0]);
                    if($ischeck == 1){
                        $this->checksendcar();
                    }
                    $isorderlist = Cm::$req->post('isorderlist', ['null', 'empty', 'default' => 0]);
                    if($isorderlist == 1){
                        $shift_id = Cm::$req->post('shift_id', ['null', 'empty', 'default' => 0]);
                        if(empty($shift_id)){
                            Cm::$res->susess(['list'=>[],'car'=>[],'inspector'=>[]]);
                        }
                        $this->getorderpassenger($shift_id);
                    }
                    break;   
                case 'changelist':
                    $id = (int)Cm::$req->post('id', ['null', 'empty', 'default' => 0]);
                    $audit=OrderChangeAudit::findOne(['change_id'=>$id]);
                    if(!$audit)Cm::$res->error("没有找到改签记录");
                    $id=$audit->first_order_id;
                    $list = Cm::$db->all("SELECT c.name as newcircuitname,b.departuretime as newdeparturetime,f.name as oldcircuitname,e.departuretime as olddeparturetime,a.addtime,a.msg,(SELECT order_number FROM `order` WHERE id=a.change_id) as auditnumber
                                FROM order_change_audit a 
                                LEFT JOIN shift b ON a.shift_id=b.id 
                                LEFT JOIN circuit c  ON b.circuit_id=c.id
                                LEFT JOIN `order` d  ON d.id=a.order_id
                                LEFT JOIN shift e ON d.shift_id=e.id 
                                LEFT JOIN circuit f  ON d.circuit_id=f.id
                                WHERE a.first_order_id={$id} AND a.status=1 ORDER BY a.addtime ASC");
                    if(empty($list)){
                        Cm::$res->error("没有找到改签记录");  
                    }else{
                        Cm::$res->susess($list);
                    }
                    break;    
                case 'changecar':
                    $isordertype = Cm::$req->post('isordertype', ['null', 'empty', 'default' => 0]);
                    $isorderlist = Cm::$req->post('isorderlist', ['null', 'empty', 'default' => 0]);
                    if(!empty($isordertype) && empty($isorderlist)){
                        $this->checkchangecircuit($isordertype);
                    }
                    if($isorderlist == 1){
                        $this->checkchangeorder($isordertype,1);
                    }
                    break;  
                case 'poolingcar':
                    $isordertype = Cm::$req->post('isordertype', ['null', 'empty', 'default' => 0]);
                    $isorderlist = Cm::$req->post('isorderlist', ['null', 'empty', 'default' => 0]);
                    if(!empty($isordertype) && empty($isorderlist)){
                        $this->checkpoolingcircuit($isordertype);
                    }
                    if($isorderlist == 1){
                        $this->checkchangeorder($isordertype,2);
                    }
                    break;       
                case 'carpoolsave':
                    $circuit_id = Cm::$req->post('circuit_id', ['null', 'empty', 'default' => 0]);
                    $shift_id = Cm::$req->post('shift_id', ['null', 'empty', 'default' => 0]);
                    $carpool_inspector = Cm::$req->post('carpool_inspector', ['null', 'empty', 'default' => 0]);
                    $carpool_shift = Cm::$req->post('carpool_shift', ['null', 'empty', 'default' => 0]);
                    $carpool_circuit = Cm::$req->post('carpool_circuit', ['null', 'empty', 'default' => 0]);
                    $carpool_car = Cm::$req->post('carpool_car', ['null', 'empty', 'default' => 0]);
                    $passenger = Cm::$req->post('passenger', ['null', 'empty', 'default' => '']);
                    $order = Cm::$req->post('order', ['null', 'empty', 'default' => '']);
                    $type = Cm::$req->post('type', ['null', 'empty', 'default' => '']);
                    if(empty($type)){
                        Cm::$res->error("请选择转车或者是拼车方式");
                    }
                    if (empty($circuit_id)) {
                        Cm::$res->error("请选择路线");
                    }
                    if (empty($shift_id)) {
                        Cm::$res->error("请选择班次");
                    }
                    if (empty($carpool_inspector)) {
                        Cm::$res->error("请选择转车车辆");
                    }
                    if (empty($carpool_car)) {
                        Cm::$res->error("请选择转车车辆");
                    }
                    if (empty($carpool_shift)) {
                        Cm::$res->error("请选择转车班次");
                    }
                    if (empty($carpool_circuit)) {
                        Cm::$res->error("请选择转车线路");
                    }
                    $passenger = empty($passenger) ? [] : json_decode($passenger,true);
                    $order = empty($order) ? [] : json_decode($order,true);
                    if (empty($passenger) || empty($order)) {
                        Cm::$res->error("请选择乘客");
                    }

                    $time = date("Y-m-d H:i:s",time());
                    $cardata = [
                        'circuit_id' => $circuit_id,
                        'shift_id' => $shift_id,
                        'carpool_id' => $carpool_shift,
                        'inspector' => $carpool_inspector,
                        'car_id' => $carpool_car,
                        'status'=>1,
                        'addtime' => $time,
                        'updatetime' => $time
                    ];
                    $ishas = Cm::$db->one("SELECT GROUP_CONCAT(order_id) AS orderids FROM order_car WHERE shift_id={$shift_id}");
                    $orderidarr = empty($ishas['orderids']) ? [] : explode(",", $ishas['orderids']); 
                    $updateorder = [];
                    foreach ($order as $key => $value) {
                        $cardata['order_id'] = $value;
                        if(!empty($orderidarr) && in_array($value, $orderidarr)){
                            Cm::$db->update('order', ['carpool_id'=>$carpool_shift,'inspector'=>$carpool_inspector,'car_id'=> $carpool_car,'updatetime'=>$time]," order_id={$value}");
                            $changeorder[] = $value;
                        }else{
                            $id = Cm::$db->insert('order_car', $cardata);
                            if($id){
                                $updateorder[] = $value;
                                Cm::$db->update('order', ['updatetime'=>$time,'order_status'=>2]," id={$value}");
                            }
                        }       
                    }
                    $seat_number = Cm::$db->one("SELECT seat_number FROM order_passenger WHERE car_id={$carpool_car} AND status=1 AND (shift_id={$carpool_shift} OR carpool_id={$carpool_shift}) ORDER BY seat_number DESC");
                    $seat_number = empty($seat_number) ? 0 : $seat_number['seat_number'];
                    foreach ($passenger as $key => $value) {
                        $seat_number++;
                        $mdata = [
                            'updatetime' =>$time,
                            'car_id'=>$carpool_car,
                            'seat_number'=>$seat_number,
                            'carpool_id' => $carpool_shift
                        ];
                        Cm::$db->update('order_passenger', $mdata," id={$value}");
                    }
                    Cm::$app->log->authlog(41,['passenger'=>$passenger,'order'=>$order,'cardata'=>$cardata],"批量派车");
                    /*发送派车模板消息*/
                    if(!empty($updateorder)){
                        $TemplateData = [
                            'order' => $updateorder
                        ];
                        Cm::$libs->wechat->sendTemplate('sendcar',$TemplateData);
                    }
                    /*发送变更通知*/
                    if(!empty($changeorder)){
                        $TemplateData = [
                            'order' => $changeorder
                        ];
                        Cm::$libs->wechat->sendTemplate('carpool',$TemplateData);
                    }
                    Cm::$res->susess([], '保存成功');
                    break;  
                case 'noticecircuit':
                    /*$page=1;
                    $size=20;*/
                    $query=OrderNotice::find()->alias('on')
                        ->leftJoin(['o'=>Order::tableName()],['on.order_id'=>new Expression('o.id')])
                        ->andWhere(['o.status'=>Order::STATUS_NORMAL,'o.order_status'=>Order::STATUS_PAID_DELIVERED])
                        ->select(['o.id','o.order_number','o.ridership','o.circuit_id','o.shift_id','on.notice_id']);
                    /*$data['count']=$query->groupBy('on.order_id')->count();*/
                    $data['data']=$query->orderBy(['on.addtime'=>SORT_DESC,'o.circuit_id'=>SORT_ASC,'o.shift_id'=>SORT_ASC])
                        ->groupBy('on.order_id')/*->limit($size)->offset(($page - 1) * $size)*/
                        ->asArray()->all();
                    $shift_ids=array_column($data['data'],'shift_id');
                    $shift=Shift::find()->andWhere(['id'=>$shift_ids])->select(['departuretime'])->indexBy('id')->column();
                    $circuit_ids=array_column($data['data'],'circuit_id');
                    $circuit=Circuit::find()->andWhere(['id'=>$circuit_ids])->select(['name'])->indexBy('id')->column();
                    foreach ($data['data'] as &$item){
                        $notice_id=OrderNotice::find()->select(['notice_id'])->andWhere(['order_id'=>$item['id']])->orderBy(['addtime'=>SORT_DESC])->scalar();
                        $notice=Notice::find()->andWhere(['id'=>$notice_id])->select(['addtime','address','plate','id'])->asArray()->one();
                        $item=array_merge($item,$notice);
                        $item['departuretime']=$shift[$item['shift_id']];
                        $item['name']=$circuit[$item['circuit_id']];
                    }



                    /*$all = Cm::$db->all("SELECT aa.*,n.addtime,n.address,n.plate FROM (
                                            SELECT a.order_number,a.id,a.ridership,
                                            (
                                                SELECT notice_id FROM order_notice WHERE a.id=order_id ORDER BY addtime DESC LIMIT 0,1
                                            ) AS notice_id,c.name,a.circuit_id,b.departuretime,a.shift_id
                                            FROM `order` a
                                            LEFT JOIN order_car oc on oc.order_id=a.id
                                            LEFT JOIN shift b ON a.shift_id=b.id
                                            LEFT JOIN circuit c  ON a.circuit_id=c.id
                                            LEFT JOIN car cr on cr.id=oc.car_id
                                            WHERE a.status=1 AND a.status=1 AND a.order_status=2 ORDER BY a.circuit_id,a.shift_id
                                        ) aa
                                        LEFT JOIN notice n ON aa.notice_id=n.id");*/
                    $all=$data['data'];
                    if(!empty($all)){
                        $car_id = 0; 
                        $shift_id = 0;
                        $circuit_id = 0;
                        foreach ($all as $key => $value) {
                            $value['isnotice'] = empty($value['notice_id']) ? 0 : 1;
                            $value['addtime'] = empty($value['addtime']) ? '' : $value['addtime'];
                            $value['address'] = empty($value['address']) ? '' : $value['address'];
                            $value['plate'] = empty($value['plate']) ? '' : $value['plate'];
                            if($circuit_id != $value['circuit_id']){
                                $circuit_id = $value['circuit_id'];
                                if(!isset($order[$circuit_id])){
                                    $order[$circuit_id] = [
                                        'list' => [],
                                        'circuit_id' => $circuit_id,
                                        'name' => $value['name']
                                    ];
                                }
                            }
                            if($shift_id != $value['shift_id']){
                                $shift_id = $value['shift_id'];
                                if(!isset($order[$circuit_id]['list'][$shift_id])){
                                    $order[$circuit_id]['list'][$shift_id] = [
                                        'departuretime' => $value['departuretime'],
                                        'shift_id' => $shift_id,
                                        'list' => []
                                    ];    
                                }
                                
                            }
                            if(!isset($order[$circuit_id]['list'][$shift_id]['list'][$value['id']])){
                                $order[$circuit_id]['list'][$shift_id]['list'][$value['id']] = $value;    
                            }
                        }
                    }else{
                        $order = '';
                    }
                    Cm::$res->susess(['list'=>$order]);
                    break;  
                case 'noticesave':
                    $shift_id = Cm::$req->post('shift_id', ['null', 'empty', 'default' => 0]);
                    $isall = Cm::$req->post('isall', ['null', 'empty', 'default' => 0]);
                    $address = Cm::$req->post('address', ['title' => '上车地址']);
                    $plate = Cm::$req->post('plate', ['title' => '车辆号']);
                    $name = Cm::$req->post('name', ['title' => '联系人']);
                    $telephone = (int)Cm::$req->post('telephone', ['title' => '联系电话']);
                    $departuretime = Cm::$req->post('departuretime', ['null', 'empty', 'default' => 0]);
                    if(empty($shift_id)){
                        Cm::$res->error("请选择通知班次");             
                    }
                    if(empty($isall)){
                        Cm::$res->error("请选择发送类型"); 
                    }
                    if(!preg_match("/^1[3456789]\d{9}$/", $telephone)){
                        Cm::$res->error('请输入正确的联系电话');
                    }
                    $noticeorder = [];
                    $time = date("Y-m-d H:i:s",time());
                    $mdata = [
                        'shift_id' => $shift_id,
                        'address' => $address,
                        'plate' =>$plate,
                        'name' => $name,
                        'telephone' => $telephone,
                        'addtime' => $time,
                        'departuretime' => $departuretime
                    ];
                    $id = Cm::$db->insert("notice",$mdata);
                    if($id){
                        $where = $isall == 1 ? " AND a.order_status=2 " : " AND a.order_status=2 AND a.id NOT IN ( SELECT order_id FROM order_notice WHERE shift_id={$shift_id} GROUP BY order_id )";
                        $order = Cm::$db->all("SELECT a.id FROM `order` a WHERE a.shift_id={$shift_id} AND a.status=1 {$where}");
                        
                        if(!empty($order)){
                            foreach ($order as $key => $value) {
                                $mdata = [
                                    'order_id' => $value['id'],
                                    'shift_id' => $shift_id,
                                    'notice_id' => $id,
                                    'addtime' => $time
                                ];
                                $rid = Cm::$db->insert("order_notice",$mdata);  
                                if($rid){
                                    $noticeorder[] = $value['id'];
                                }
                            }
                        }
                        /*发送变更通知*/
                        if(!empty($noticeorder)){
                            $TemplateData = [
                                'order' => $noticeorder,
                                'plate' => $plate,
                                'address' => $address,
                                'name' => $name,
                                'telephone' => $telephone,
                                'departuretime' => $departuretime
                            ];
                            Cm::$libs->wechat->sendTemplate('notice',$TemplateData);
                        }
                        Cm::$res->susess([]);
                    }else{
                        Cm::$res->error("发送通告失败");     
                    }
                    break; 
                case 'refund':
                    $id = (int)Cm::$req->post('id', ['null', 'empty', 'default' => 0]);
                    if(empty($id)){
                        Cm::$res->error("请选择退款的订单");         
                    }
                    /*是否是改签单*/
                    $has = Cm::$db->one("SELECT first_order_id FROM order_change_audit WHERE change_id={$id} ");
                    $info = Cm::$db->one("SELECT a.order_number,a.pay_type,a.pay_price,a.circuit_id,b.departuretime FROM `order` a LEFT JOIN shift b on b.id=a.shift_id WHERE a.id={$id} AND a.status=1 AND a.order_status=1");
                    if(empty($info)){
                        Cm::$res->error("订单不存在");
                    }
                    if($has) {
                        $has_info = Cm::$db->one("SELECT a.order_number,a.pay_type,a.pay_price,a.circuit_id,b.departuretime FROM `order` a LEFT JOIN shift b on b.id=a.shift_id WHERE a.id={$has['first_order_id']} ");
                        if(empty($has_info))Cm::$res->error("订单不存在");
                        $info['order_number']=$has_info['order_number'];
                    }
                    $this->refundorder($info,$id);
                    break;                      
            }
            Cm::$res->error("参数错误"); 
        }
        $data['map'] = [];
        $data['map'][] = ['title' => "订单管理", 'url' => Url::to(['order/index'])];
        $data['baseUrl'] = Url::to(['order/index']);
        $data['carallplate'] = $this->getCarAllPlate();
        $data['allssite'] = $this->getAllShiftSsite();
        $data['allesite'] = $this->getAllShiftEsite();
        $data['allcircuit'] = $this->getAllCircuit();

        return $data;
    }

    /*
    *导出订单
    */
    public function actionDownexport(){
        set_time_limit(0);
        ini_set('memory_limit', '2048M');
        $params=Yii::$app->request->get();

        $query=Order::find()->alias('o')
            ->with(['orderPassenger'=>function($q){
                $q->select(['id','order_id','name','telephone','id_card']);
            }])
            ->leftJoin(['s'=>Shift::tableName()],['o.shift_id'=>new Expression('s.id')])
            ->leftJoin(['c'=>Circuit::tableName()],['o.circuit_id'=>new Expression('c.id')])
            ->select([
                'o.id','o.order_number','o.status','o.order_status','o.shift_id','o.p_id','o.s_id','o.e_id','s.departuretime','s.inspector',
                'c.name as circuit_name','c.s_address','c.e_address','c.city_scode','c.city_ecode','c.site_sid','c.site_eid',
            ])
            ->andWhere(['s.status'=>Enum::STATUS_NORMAL,'c.status'=>Enum::STATUS_NORMAL]);

       if(!empty($params['order_status']))$query->andWhere(['o.order_status'=>$params['order_status']]);

        if(!empty($params['status']))$query->andWhere(['o.status'=>$params['status']]);

        if(!empty($params['plate'])){
            $order_ids=OrderCar::find()->andWhere(['car_id'=>$params['plate']])->select(['order_id'])->groupBy('order_id')
                ->column();
            $query->andWhere(['o.id'=>$order_ids]);
        }
        if(!empty($params['circuit']))$query->andWhere(['o.circuit_id'=>$params['circuit']]);

        if(!empty($params['key']) || (isset($params['key'])&&$params['key'] == 0)){
            $order_ids=OrderPassenger::find()->andWhere(['or',
                ['like','name',$params['key']],
                ['like','telephone',$params['key']],
                ['like','id_card',$params['key']],
            ])->select('order_id')->groupBy('order_id')->column();
            $query->andWhere([
                'or',
                ['like','o.order_number',$params['key']],
                ['o.id'=>$order_ids]
            ]);
        }

        if(!empty($params['type']))$query->andWhere(['s.type'=>$params['type']]);

        if(!empty($params['departuretime'])){
            $departuretimearr = explode("至", $params['departuretime']);
            $stime = trim($departuretimearr[0]);
            $etime = trim($departuretimearr[1]);
            $query->andWhere(['between','s.departuretime',$stime,$etime]);
        }

        if (!empty($params['ssite']))$query->andWhere(['c.site_sid'=>$params['ssite']]);

        if (!empty($params['esite']))$query->andWhere(['c.site_eid'=>$params['esite']]);

        $total=$query->count();
        $page=1;
        $size=1000;
        $data_all=[];
        $open_city=OpenCity::find()->select(['name'])->indexBy('code')->column();
        $site=Site::find()->indexBy('id')->asArray()->all();
        if($total>$page){
            while (true){
                $data=$this->order_query((clone $query),[$page,$size,$open_city,$site]);
                if(!count($data))break;
                $page++;
                $data_all=array_merge($data_all,$data);
            }
        }else{
            $data=$this->order_query((clone $query),[$page,$size,$open_city,$site]);
            $data_all=$data;
        }

        $list=$data_all;
        $objPHPExcel = Cm::$libs->PHPExcel();
        $objPHPExcel->getProperties()
            ->setTitle('Office 2007 XLSX Test Document')
            ->setSubject('Office 2007 XLSX Test Document')
            ->setDescription('Test document for Office 2007 XLSX, generated using PHP classes.')
            ->setKeywords('office 2007 openxml php')
            ->setCategory('Test result file');
        $objPHPExcel->getActiveSheet()->setTitle('订单信息');
        $objPHPExcel->getActiveSheet()
            ->setCellValue('A1', '订单编号')
            ->setCellValue('B1', '车牌号')
            ->setCellValue('C1', '发车时间')
            ->setCellValue('D1', '起始站点')
            ->setCellValue('E1', '目的站点')
            ->setCellValue('F1', '起始地')
            ->setCellValue('G1', '目的地')
            ->setCellValue('H1', '订单状态')
            ->setCellValue('I1', '客户姓名')
            ->setCellValue('J1', '客户手机号')
            ->setCellValue('K1', '客户身份证');

        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(30);
        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(15);
        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(30);
        $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(30);
        $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(30);
        $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(30);
        $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(30);
        $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(15);
        $objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(30);
        $objPHPExcel->getActiveSheet()->getColumnDimension('K')->setWidth(30);
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $order_number = '';
        if(!Cm::$redis->Exists('is_err')){
            if(!empty($list)){
                foreach ($list as $i => $item) {
                    $row = $i + 2;
//                if($order_number != $item['order_number']){
//                    $order_number = $item['order_number'];
                    $plate = empty($item['plate'])?"":$item['plate'];
                    $sname = $item['citysname'].'-'.$item['sitesname'];
                    $ename = $item['cityename'].'-'.$item['siteename'];
                    $status = $this->getstatusstr($item['status'],$item['order_status']);
                    $objPHPExcel->getActiveSheet()->setCellValueExplicit('A' . $row, $item['order_number'], PHPExcel_Cell_DataType::TYPE_STRING);
                    $objPHPExcel->getActiveSheet()
                        ->setCellValue('B' . $row, $plate)
                        ->setCellValue('C' . $row, $item['departuretime'])
                        ->setCellValue('D' . $row, $item['sitesname'])
                        ->setCellValue('E' . $row, $item['siteename'])
                        ->setCellValue('F' . $row, $sname)
                        ->setCellValue('G' . $row, $ename)
                        ->setCellValue('H' . $row, $status);
//                }
                    $objPHPExcel->getActiveSheet()->setCellValue('I' . $row, $item['username']);
                    $objPHPExcel->getActiveSheet()->getStyle('I' . $row)->getAlignment()->setWrapText(true)->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
                    $objPHPExcel->getActiveSheet()->setCellValueExplicit('J' . $row, $item['telephone'], PHPExcel_Cell_DataType::TYPE_STRING);
                    $objPHPExcel->getActiveSheet()->getStyle('J' . $row)->getAlignment()->setWrapText(true)->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
                    $objPHPExcel->getActiveSheet()->setCellValueExplicit('K' . $row, $item['idcard'], PHPExcel_Cell_DataType::TYPE_STRING);
                    $objPHPExcel->getActiveSheet()->getStyle('K' . $row)->getAlignment()->setWrapText(true)->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
                }
            }
        }
        $objPHPExcel->getDefaultStyle()->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('D')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
        $objPHPExcel->getActiveSheet()->getStyle('E')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
        $objPHPExcel->getActiveSheet()->getStyle('F')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
        $objPHPExcel->getActiveSheet()->getStyle('G')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
        $objPHPExcel->getActiveSheet()->getStyle('I')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
        $objPHPExcel->getActiveSheet()->getStyle('D1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('E1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('F1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('G1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('I1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getDefaultStyle()->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        
        $filename = date("Y年m月d日 H:i",time()).'的订单信息';

        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $filename . '.xlsx"');
        header('Cache-Control: max-age=0');
        $objWriter->save('php://output');
        exit;
    }

    public function order_query(Query $query,$params){
        [$page,$size,$open_city,$site]=$params;
        $data=(clone $query)->limit($size)->offset(($page - 1) * $size)
            ->orderBy('o.addtime desc')->asArray()->all();
        if(!count($data))return [];
        $pt_ids=array_filter(array_unique(array_column($data,'p_id')));
        $departuretime=[];
        if(count($pt_ids)){
            $departuretime=PointTime::find()->andWhere(['id'=>$pt_ids])->select(['departuretime'])->indexBy('id')->column();
        }
        $ids=array_column($data,'id');
        $car=Car::find()->alias('c')
            ->leftJoin(['oc'=>OrderCar::tableName()],['c.id'=>new Expression('oc.car_id')])
            ->andWhere(['oc.order_id'=>$ids])
            ->select(['c.plate','oc.order_id'])
            ->indexBy('order_id')->column();
//        $order_passenger=OrderPassenger::find()->andWhere(['order_id'=>$ids])
//            ->select(['name','telephone','id_card','order_id'])
//            ->indexBy('order_id')
//            ->asArray()
//            ->all();
        $s_ids=array_column($data,'s_id');
        $e_ids=array_column($data,'e_id');
        $site_ids=CircuitAddress::find()->andWhere(['id'=>array_merge($s_ids,$e_ids)])
            ->select(['site_id','id'])->indexBy('id')->column();
        $all_data=[];
        foreach ($data  as $value){
            $value['departuretime']=$departuretime[$value['p_id']]??$value['departuretime'];
            if(!$value['s_id']){
                $s_city=$value['city_scode'];
                $s_site=$value['site_sid'];
            }else{
                $s_city=$site[$site_ids[$value['s_id']]]['city_code']??'';
                $s_site=$site_ids[$value['s_id']];
            }

            if(!$value['e_id']){
                $e_city=$value['city_ecode'];
                $e_site=$value['site_eid'];
            }else{
                $e_city=$site[$site_ids[$value['e_id']]]['city_code']??'';
                $e_site=$site_ids[$value['e_id']];
            }

            $value['citysname']=$open_city[$s_city]??'';
            $value['cityename']=$open_city[$e_city]??'';
            $value['sitesname']=$site[$s_site]['name']??'';
            $value['siteename']=$site[$e_site]['name']??'';
            $value['plate']=$car[$value['id']]??'';
            foreach ($value['orderPassenger'] as $item){
                $value['username']=$item['name'];
                $value['telephone']=$item['telephone'];
                $value['idcard']=$item['id_card'];
                $all_data[]=$value;
            }
            /*$value['username']=implode(array_column($value['orderPassenger'],'name'),PHP_EOL);
            $value['telephone']=implode(array_column($value['orderPassenger'],'telephone'),PHP_EOL);
            $value['idcard']=implode(array_column($value['orderPassenger'],'id_card'),PHP_EOL);*/
        }
        return $all_data;
    }

    /*获取订单的状态*/
    private function getstatusstr($status,$order_status){
        $msg = "";
        if($status == 1){
            switch ($order_status) {
                case 0:
                    $msg = "未支付";
                    break;
                case 1:
                    $msg = "待出票";
                    break;
                case 2:
                    $msg = "待出行";
                    break;  
                case 3:
                    $msg = "已发车";
                    break;
                case 4:
                    $msg = "已完成";
                    break;  
            }
        }else if($status == 2){
            $msg = "已删除";
        }else if($status == 0){
            $msg = "已取消";
        }else if($status == 3){
            $msg = "已改签";
        }else if($status == 4){
            $msg = "已退款";
        }
        return $msg;
    }

    /*
    *获取未派车的订单乘客
    */
    private function getorderpassenger($shift_id){
        $order = [];
        $list = Cm::$db->all("SELECT a.id,a.order_number,a.addtime,a.ridership,b.id AS passenger_id,b.name,b.id_card,b.telephone  
                            FROM order_passenger b
                            LEFT JOIN `order` a ON b.order_id=a.id 
                            WHERE a.shift_id={$shift_id} AND a.order_status=1 AND a.status=1 AND b.car_id=0 AND b.seat_number=0 ORDER BY order_id");
        $order = [];
        $ids = 0;
        if(!empty($list)){
            $order_number = "";
            foreach ($list as $key => $value) {
                if($order_number != $value['order_number']){
                    $order_number = $value['order_number'];
                    $ids ++;
                    $order[] = [
                        'ridership' => $value['ridership'],
                        'ridershipstr' => $value['ridership'].'人', 
                        'order_number' => $order_number,
                        'order_id' => $value['id'],
                        'ids' => $ids,
                        'addtime' => $value['addtime'],
                        'passenger' => []
                    ];
                }
                $num = count($order)-1;
                $order[$num]['passenger'][] = $value; 
            }
        }
        $shiftinfo = Cm::$db->one("SELECT models_id,departuretime FROM shift WHERE id={$shift_id}");
        $where = $shiftinfo['models_id'] == 0 ? "" : " AND a.models_id={$shiftinfo['models_id']} ";
        $car = Cm::$db->all("SELECT a.id,a.p_seat,a.plate,
                            (
                                SELECT COUNT(id) as num 
                                FROM order_passenger 
                                WHERE (shift_id={$shift_id} OR carpool_id={$shift_id} ) AND car_id=a.id AND status=1
                            ) AS seatnum,
                            (
                                SELECT CONCAT_WS('  ',departuretime,(
                                    SELECT CONCAT_WS('--',CONCAT_WS('/',oa.name,sa.name) ,CONCAT_WS('/',ob.name,sb.name)) AS name 
                                    FROM circuit cc 
                                    INNER JOIN open_city oa ON oa.code=cc.city_scode
                                    INNER JOIN open_city ob ON ob.code=cc.city_scode 
                                    INNER JOIN site sa ON sa.id=cc.site_sid 
                                    INNER JOIN site sb ON sb.id=cc.site_eid 
                                    WHERE cc.id=oc.circuit_id AND cc.status=1 AND sa.status=1 AND sb.status=1 AND oa.status=1 AND ob.status=1
                                )) AS lasttime
                                FROM order_car oc
                                INNER JOIN shift st ON st.id=oc.shift_id
                                WHERE oc.car_id=a.id AND st.departuretime<'{$shiftinfo['departuretime']}'
                                GROUP BY oc.shift_id
                                ORDER BY st.departuretime DESC LIMIT 0,1
                            ) AS lasttime,
                            (
                                SELECT CONCAT_WS('  ',departuretime,(
                                    SELECT CONCAT_WS('--',CONCAT_WS('/',oa.name,sa.name) ,CONCAT_WS('/',ob.name,sb.name)) AS name 
                                    FROM circuit cc 
                                    INNER JOIN open_city oa ON oa.code=cc.city_scode
                                    INNER JOIN open_city ob ON ob.code=cc.city_scode 
                                    INNER JOIN site sa ON sa.id=cc.site_sid 
                                    INNER JOIN site sb ON sb.id=cc.site_eid 
                                    WHERE cc.id=oc.circuit_id AND cc.status=1 AND sa.status=1 AND sb.status=1 AND oa.status=1 AND ob.status=1
                                )) AS nexttime
                                FROM order_car oc
                                INNER JOIN shift st ON st.id=oc.shift_id
                                WHERE oc.car_id=a.id AND st.departuretime>'{$shiftinfo['departuretime']}'
                                GROUP BY oc.shift_id
                                ORDER BY st.departuretime ASC LIMIT 0,1
                            ) AS nexttime
                            FROM car a 
                            WHERE a.status=1 {$where} AND a.id NOT IN (
                                SELECT oc.car_id FROM order_car oc 
                                INNER JOIN shift st ON st.id=oc.shift_id
                                WHERE st.departuretime='{$shiftinfo['departuretime']}' 
                                GROUP BY oc.car_id
                            ) OR a.id IN (
                                SELECT oc.car_id FROM order_car oc 
                                WHERE oc.shift_id = {$shift_id}
                                GROUP BY oc.car_id
                            )
                            HAVING a.p_seat > seatnum ");
        if(!empty($car)){
            foreach ($car as $key => $value) {
                $car[$key]['lasttime'] = empty($value['lasttime']) ? '无' : $value['lasttime'];
                $car[$key]['nexttime'] = empty($value['nexttime']) ? '无' : $value['nexttime'];                    
            }
        }else{
            $car = [];
        }
        $inspector = $this->getInspector();
        Cm::$res->susess(['list'=>$order,'car'=>$car,'inspector'=>$inspector]);
    }

    /*
    *检查是否有未派车的已付款订单
    */
    private function checksendcar(){
        $time = date("Y-m-d H:i:s",time());
        $ishas = Cm::$db->all("SELECT a.circuit_id,b.name,a.shift_id,c.departuretime,c.models_id,c.inspector FROM `order` a 
                                LEFT JOIN circuit b ON b.id=a.circuit_id
                                LEFT JOIN shift c ON c.id=a.shift_id
                                WHERE a.status=1 AND a.order_status=1 AND b.status=1 AND c.status=1 AND c.departuretime>'{$time}' AND a.is_check=0
                                GROUP BY a.shift_id ORDER BY a.circuit_id,c.departuretime");
        if(empty($ishas)){
            Cm::$res->error("没有可以查询到订单");
        }else{
            $data = [];
            $circuit_id = 0;
            foreach ($ishas as $key => $value) {
                if($value['circuit_id'] != $circuit_id){
                    $circuit_id = $value['circuit_id'];
                    $data[$circuit_id] = [
                        'shift' => [],
                        'circuit_id' => $circuit_id,
                        'name' => $value['name']
                    ];
                }
                $data[$circuit_id]['shift'][$value['shift_id']] = $value;
            }
            Cm::$res->susess($data);
        }
    }

    /*
    *检查是否有已派车的已付款订单
    */
    private function checksendcarok(){
        $time = date("Y-m-d H:i:s",time());
        $ishas = Cm::$db->all("SELECT a.circuit_id,b.name,a.shift_id,c.departuretime,c.models_id,c.inspector FROM `order` a 
                                LEFT JOIN circuit b ON b.id=a.circuit_id
                                LEFT JOIN shift c ON c.id=a.shift_id
                                WHERE a.status=1 AND a.order_status=2 AND b.status=1 AND c.status=1 AND c.departuretime>'{$time}' AND a.is_check=0
                                GROUP BY a.shift_id ORDER BY a.circuit_id,c.departuretime");
        if(empty($ishas)){
            Cm::$res->error("没有可以查询到订单");
        }else{
            $data = [];
            $circuit_id = 0;
            foreach ($ishas as $key => $value) {
                if($value['circuit_id'] != $circuit_id){
                    $circuit_id = $value['circuit_id'];
                    $data[$circuit_id] = [
                        'shift' => [],
                        'circuit_id' => $circuit_id,
                        'name' => $value['name']
                    ];
                }
                $data[$circuit_id]['shift'][$value['shift_id']] = $value;
            }
            Cm::$res->susess($data);
        }
    }

    /*检查获取转车或者派车订单类型线路*/
    private function checkchangecircuit($ordertype){
        if($ordertype == 1){
            $this->checksendcar();
        }else{
            $this->checksendcarok();
        }
    }

    private function checkpoolingcircuit($ordertype)
    {
        if($ordertype == 1){
            $this->checksendcar();
        }else{
            $this->checksendcarok();
        }
    }

    /*检查获取所有未发车的已付款订单*/
    private function checkchangeorder($isordertype,$type){
        $shift_id = Cm::$req->post('shift_id', ['null', 'empty', 'default' => 0]);
        $order = [];
        $carpoolcircuit = [];
        
            if(empty($shift_id)){
                Cm::$res->susess(['list'=> $order,'carpoolcircuit'=>$carpoolcircuit]);
            }
            $listwhere = $isordertype == 1 ? " AND a.order_status=1 AND a.status=1 AND b.car_id=0 AND b.seat_number=0 " : " AND a.order_status=2 AND a.status=1 AND b.car_id!=0 AND b.seat_number!=0 AND c.status=1 HAVING c.p_seat!=seatnum ";
            $list = Cm::$db->all("SELECT a.id,a.order_number,a.addtime,a.ridership,b.id AS passenger_id,b.name,b.id_card,b.telephone,(
                                SELECT COUNT(id) as num 
                                FROM order_passenger 
                                WHERE (shift_id={$shift_id} OR carpool_id={$shift_id} ) AND car_id=c.id AND status=1
                            ) AS seatnum,c.p_seat,b.car_id,c.plate  
                                FROM order_passenger b
                                LEFT JOIN `order` a ON b.order_id=a.id 
                                LEFT JOIN car c ON c.id=b.car_id
                                WHERE a.shift_id={$shift_id} {$listwhere} ORDER BY b.car_id,b.order_id");
            $ids = 0;
            $car = [];
            if(!empty($list)){
                $order_number = "";
                $car_id = 0;
                foreach ($list as $key => $value) {
                    if($order_number != $value['order_number']){
                        $order_number = $value['order_number'];
                        $ids ++;
                        $order[] = [
                            'ridership' => $value['ridership'],
                            'ridershipstr' => $value['ridership'].'人', 
                            'order_number' => $order_number,
                            'order_id' => $value['id'],
                            'ids' => $ids,
                            'addtime' => $value['addtime'],
                            'passenger' => [],
                            'car_id' => $value['car_id']
                        ];
                        if($car_id != $value['car_id']){
                            $car_id = $value['car_id'];
                            if(!isset($car[$car_id])){
                                $car[$car_id] = [
                                    'id' => $car_id,
                                    'p_seat' => $value['p_seat'],
                                    'seatnum' => $value['seatnum'],
                                    'plate' => $value['plate']
                                ];
                            }
                        }
                    }
                    $num = count($order)-1;
                    $order[$num]['passenger'][] = $value; 
                }
            }
            $shiftinfo = Cm::$db->one("SELECT st.departuretime,ct.site_sid,ct.site_eid FROM shift st
                                        LEFT JOIN circuit ct ON ct.id=st.circuit_id
                                        WHERE st.id={$shift_id} AND ct.status=1");
            $where = $type == 1 ? " AND st.departuretime='{$shiftinfo['departuretime']}'  AND ct.site_sid={$shiftinfo['site_sid']} " : " AND st.departuretime<'{$shiftinfo['departuretime']}'  AND ct.site_eid={$shiftinfo['site_eid']}";
            $allcarpool = Cm::$db->all("SELECT a.*,a.car_id AS id,c.plate,c.p_seat,d.name,e.departuretime,(
                                        SELECT COUNT(id) as num 
                                        FROM order_passenger 
                                        WHERE (shift_id=a.shift_id OR carpool_id=a.shift_id ) AND car_id=a.car_id AND status=1
                                        ) seatnum FROM (
                                        SELECT oc.car_id,oc.shift_id,oc.circuit_id,oc.inspector
                                        FROM order_car oc
                                        WHERE oc.shift_id IN (
                                            SELECT st.id
                                            FROM shift st
                                            INNER JOIN circuit ct on ct.id=st.circuit_id
                                            WHERE ct.status=1 {$where} AND st.status=1
                                        ) AND oc.shift_id!={$shift_id}
                                        GROUP BY oc.circuit_id,oc.shift_id,oc.car_id
                                    ) a 
                                    LEFT JOIN car c ON c.id=a.car_id
                                    INNER JOIN circuit d ON d.id=a.circuit_id
                                    INNER JOIN shift e ON e.id=a.shift_id
                                    HAVING c.p_seat>seatnum 
                                    ORDER BY a.circuit_id,a.shift_id,a.car_id");
            $carpool = [];
            if(!empty($allcarpool)){
                $circuit_id = 0;
                $shift_id = 0;
                foreach ($allcarpool as $key => $value) {
                    if($circuit_id != $value['circuit_id']){
                        $circuit_id = $value['circuit_id'];
                        $circuit = [
                            'name' => $value['name'],
                            'circuit_id' => $circuit_id,
                            'list' => []
                        ];
                        if(!isset($carpool[$circuit_id])){
                            $carpool[$circuit_id] = $circuit;    
                        }
                    }
                    if($shift_id != $value['shift_id']){
                        $shift_id = $value['shift_id'];
                        $shift = [
                            'departuretime' => $value['departuretime'],
                            'shift_id' => $shift_id,
                            'list' => []
                        ];
                        if(!isset($carpool[$circuit_id]['list'][$shift_id])){
                            $carpool[$circuit_id]['list'][$shift_id] = $shift;    
                        }
                        
                    }
                    if(!isset($carpool[$circuit_id]['list'][$shift_id]['list'][$value['id']])){
                        $carpool[$circuit_id]['list'][$shift_id]['list'][$value['id']] = $value;    
                    }
                }
            }
            Cm::$res->susess(['list'=>$order,'carpool'=>$carpool,'car'=>$car]);
    }

    /*发送模板消息*/
    private function sendTemplate($data){
        $TemplateData = [
            'openid' => $data['openid'],
            'order_number' => $data['order_number'],
            'audit_time' => date("Y年m月d日 H:i:s",$data['time']),
            'audit_str' => $data['change_audit'] == 1 ? '通过' : '拒绝',
            'remark' => empty($data['msg']) ? '' : $data['msg'],
            'newcircuit' => '您的'.$data['name'].'线路改签班次为:'.$data['departuretime'].'的审核结果如下：'
        ];
        Cm::$libs->wechat->sendTemplate('audit',$TemplateData);
    }

    /*退款*/
    private function refundorder($info,$order_id){
        $time = time();
        $timestr = date("Y-m-d H:i:s",$time);
        $departuretime = strtotime($info['departuretime']);
        /*退款金额*/
        $refund_amount = $info['pay_price'];
        $refund_service = 0;
        $isall = Cm::$db->one("SELECT `value` FROM rule_setting WHERE type=6 AND  circuit_id={$info['circuit_id']} AND status=1");
        if(empty($isall)){
            $isall = Cm::$db->one("SELECT `value` FROM rule_setting WHERE type=6 AND  circuit_id=0 AND status=1");
            $alltimenum = empty($isall) ? 0 : (int)$isall['value'];
        }else{
            $alltimenum = (int)$isall['value'];
        }
        $isok = 0;
        if($alltimenum != 0){
            $alltime = strtotime("-".$alltimenum." day",$departuretime);
            if($time <= $alltime){
                /*全款退*/
                $isok = 1;
            }
        }
        if($isok == 0){
            /*部分*/
            $isone = Cm::$db->one("SELECT `value` FROM rule_setting WHERE type=8 AND  circuit_id={$info['circuit_id']} AND status=1");
            if(empty($isone)){
                $isone = Cm::$db->one("SELECT `value` FROM rule_setting WHERE type=8 AND  circuit_id=0 AND status=1");
            }
            if(!empty($isone)){
                $rule = json_decode($isone['value'],true);
                foreach ($rule['start'] as $key => $value) {
                    $starttime = $value == 0 ?  $departuretime : strtotime("-".$value." day",$departuretime);
                    $endtime = strtotime("-".$rule['end'][$key]." day",$departuretime);
                    $service = $rule['service'][$key]; 
                    if($key == 0 && $time >= $endtime){
                        $isok = 1;
                    }elseif ($key != 0 && $time >= $endtime && $time < $starttime) {
                        $isok = 1;
                    }
                    if($isok == 1){
                        $refund_service = sprintf("%.2f",$refund_amount*$service/100);
                        $refund_amount = $refund_service > 0 ? sprintf("%.2f",$refund_amount-$refund_service) : $refund_amount;
                        if($refund_amount>$info['pay_price']){
                            $refund_amount = $info['pay_price'];
                            $refund_service = 0;    
                        }
                        break;
                    }
                }
            }
        }
        /*退款单号*/
        $refund_number = "R".$info['order_number'];
        if($info['pay_type'] == 1){
            $config = Yii::$app->params['wechat']['open'];
            $paySdk = Cm::$libs->wechat->pay($config['appid']);
            $goods = [
                "out_trade_no" => $info['order_number'],
                "out_refund_no" => $refund_number,
                "refund_fee" => $refund_amount*100,
                "total_fee" => $info['pay_price'] * 100,
                "notify_url" => BASE_URL . Url::to(['/wechat/order/refundnotify2'])
            ];
            $res = $paySdk->orderrefund($goods);
            $refund_status = 0;
        }else{
            $config = Yii::$app->params['alipay'];
            $config['public_key'] = $this->getPublicKey($config['app_cert']);
            $goods = [
                'out_trade_no' => $info['order_number'],
                'refund_amount' => $refund_amount
            ];
            $result = Cm::$libs->wechat->alirefund($config,$goods);
            $res = array("flag" => false, "msg" => "", "data" => array());
            Cm::$app->log->common('alirefund', $result);
            if($result['code'] == 10000 && $result['msg'] == 'Success'){
                $res['flag'] = true;
                $refund_status = 1;
            }else{
                $res['msg'] = $result['sub_msg'];
            }
        }
        
        if($res['flag']){
            $mdata = [
                'status' => 4,
                'order_status' => 5,
                'updatetime' => $timestr,
                'refund_amount' => $refund_amount,
                'refund_service' => $refund_service,
                'refund_number' => $refund_number,
                'refund_time' => $timestr,
                'refund_status' => $refund_status
            ];
            Cm::$db->update("order", $mdata," id={$order_id}");
            if($info['pay_type'] == 2){
                //发送退款成功通知
                $TemplateData = [
                    'order_id' => $order_id,
                ];
                Cm::$libs->wechat->sendTemplate('refund2',$TemplateData);
            }
            Cm::$res->susess([],"退款申请成功");
        }else{
            Cm::$res->error($res['msg']);
        }
    }

    /**
     * 从证书中提取公钥
     * @param $certPath
     * @return mixed
     */
    private function getPublicKey($certPath)
    {
        $cert = file_get_contents($certPath);
        $pkey = openssl_pkey_get_public($cert);
        $keyData = openssl_pkey_get_details($pkey);
        $public_key = str_replace('-----BEGIN PUBLIC KEY-----', '', $keyData['key']);
        $public_key = trim(str_replace('-----END PUBLIC KEY-----', '', $public_key));
        $public_key = preg_replace(['/\s+/', '/\-{5}.*?\-{5}/'], '', $public_key);
        return $public_key;
    }
}